﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Xna.Framework.Graphics;
using RaisingStudio.SmallProgram.Library.Internal;

namespace RaisingStudio.SmallProgram.Library
{
    [SmallProgramType]
    public static class ImageList
    {
        private static Dictionary<string, Texture2D> _savedImages = new Dictionary<string, Texture2D>();

        internal static Texture2D GetBitmap(Primitive imageName)
        {
            Texture2D source = null;
            if (!imageName.IsEmpty)
            {
                _savedImages.TryGetValue((string)imageName, out source);
            }
            if (source == null)
            {
                source = LoadImageFromFile(imageName);
            }
            return source;
        }

        internal static Texture2D LoadImageFromFile(Primitive fileNameOrUrl)
        {
            Primitive localFileName = Network.GetLocalFile(fileNameOrUrl);
            return (Texture2D)SmallProgramApplication.InvokeWithReturn(delegate
            {
                try
                {
                    System.IO.FileStream fileStream = new System.IO.FileStream(localFileName, System.IO.FileMode.Open);
#if MonoGame                    
                    return Texture2D.FromFile(GraphicsWindow.GraphicsDevice, fileStream);
#else
                    return Texture2D.FromStream(GraphicsWindow.GraphicsDevice, fileStream);
#endif
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.ToString());
                    return null;
                }
            });
        }

        public static Primitive GetHeightOfImage(Primitive imageName)
        {
            Texture2D image = GetBitmap(imageName);
            if (image == null)
            {
                return 0;
            }
            return (Primitive)GraphicsWindow.InvokeWithReturn(delegate
            {
                return (Primitive)image.Height;
            });
        }

        public static Primitive GetWidthOfImage(Primitive imageName)
        {
            Texture2D image = GetBitmap(imageName);
            if (image == null)
            {
                return 0;
            }
            return (Primitive)GraphicsWindow.InvokeWithReturn(delegate
            {
                return (Primitive)image.Width;
            });
        }

        public static Primitive LoadImage(Primitive fileNameOrUrl)
        {
            if (fileNameOrUrl.IsEmpty)
            {
                return "";
            }
            string imageName = Shapes.GenerateNewName("ImageList");
            _savedImages[imageName] = LoadImageFromFile(fileNameOrUrl);
            return imageName;
        }
    }
}

